package middleware;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;

// Listens to initial connections from clients.
// Single thread that handles all requests.
// Once the request is handled, the listener does not do anything else.
public class Listener extends Thread{
	
	private Properties properties = new Properties();
	private Integer portNr;
	private ArrayList<Integer> mwPorts;
	/**
	 * @uml.property  name="queue"
	 * @uml.associationEnd  
	 */
	private Queue queue;
	
	
	/**
	 * Reads needed properties from config file and is initialized with a queue.
	 * @param q Queue.
	 */
	public Listener(Queue q) {
		super();
		FileInputStream iStream;
		try {
			iStream  = new FileInputStream("config/config.properties");
			properties.load(iStream);
			iStream.close();
		} catch (FileNotFoundException e) {
			System.err.println("File not found: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("IO error: " + e.getMessage());
		}

		String portsString = properties.getProperty("mwPortNr");
		mwPorts = new ArrayList<Integer>();
		StringTokenizer st = new StringTokenizer(portsString, ",");
		while (st.hasMoreTokens()) {
			mwPorts.add(new Integer(st.nextToken()));
		}
		
		// use first port in list
		portNr = mwPorts.get(0);
		
		queue = q;
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		ServerSocket socketListener = null;
		Socket acceptSocket = null;
		
		try {
			socketListener = new ServerSocket(portNr);
		} catch (IOException e) {
			System.out.println(e);
	    }
		
		while(true) {
			try {
				acceptSocket = socketListener.accept();
			} catch (IOException e) {
				System.out.println(e);
	        }
			
			ClientHandler clientHandler = new ClientHandler(acceptSocket, queue);
			clientHandler.start();
			
		}
	}
}
